import {
	dateTypeFormat
} from "@/uitls/tool.js"
export default {
	namespaced: true,
	state: {
		allData: uni.getStorageSync("allData") || {
			tag: "AccountBook"
		},
		yusuanData: uni.getStorageSync("yusuanData") || {},
	},
	mutations: {
		updateData(state) {
			const allDataChanged = JSON.stringify(state.allData) !== JSON.stringify(uni.getStorageSync("allData"));
			const yusuanDataChanged = JSON.stringify(state.yusuanData) !== JSON.stringify(uni.getStorageSync(
				"yusuanData"));
			if (allDataChanged) {
				uni.$emit('updateStatistics') // 切换 统计页 更新
				uni.$emit('updateIndex') // 主页更新
				uni.setStorageSync('allData', state.allData)
			}
			if (yusuanDataChanged) {
				uni.setStorageSync('yusuanData', state.yusuanData)
			}
		},
		addAllData(state, data) {
			let [year, month, day] = data.timeValue.split("-");
			let haveMountd = `${year}-${month}`;
			if (state.allData[haveMountd] == null) {
				state.allData[haveMountd] = []
			}
			state.allData[haveMountd].push(data)
			state.allData[haveMountd].sort((a, b) => new Date(a.timeValue) - new Date(b.timeValue));
			this.commit("mainData/updateData")
		},
		deleteOneData(state, data) { // 删除记录
			const {
				theMonth,
				theOne
			} = data
			let theMonthData = state.allData[theMonth]
			theMonthData.splice(theMonthData.indexOf(theOne), 1)
			if (theMonthData.length <= 0) { // 删掉 多余的空数组
				delete state.allData[theMonth];
			}
			this.commit("mainData/updateData")
		},
		chanegAllData(state, data) {
			const {
				newData,
				oldData
			} = data
			this.commit("mainData/deleteOneData", {
				theMonth: dateTypeFormat("YYYY-mm", new Date(oldData.timeValue)),
				theOne: oldData
			})
			this.commit("mainData/addAllData", newData)
		},
		addYusuanData(state, data) { // 预算
			const time = data.time
			if (state.yusuanData[time] == null) {
				state.yusuanData[time] = []
			}
			const index = state.yusuanData[time].findIndex(item => item.tag === data.tag);
			if (index !== -1) {
				// 如果找到了相同标签的预算，更新其金额
				state.yusuanData[time][index].sum = (parseFloat(state.yusuanData[time][index].sum) + parseFloat(data
						.sum))
					.toString();
			} else {
				// 如果没有找到相同标签的预算，添加新的预算项
				state.yusuanData[time].push(data);
			}
			this.commit("mainData/updateData")
		},
		deleteYusuanData(state, data) { // 删除预算
			state.yusuanData[data.time] = state.yusuanData[data.time].filter(item => {
				if (item.tag == data.tag) return false
				return true
			})
			this.commit("mainData/updateData")
		},
	},
}